﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mc.Fe.Entities;
using Mc.Fe.Logic;
using System.IO;
using System.Net.Mail;
using System.Net;
using Mc.Fe.WcfService;
using Mc.Fe.WcfService.webEfact;
using Mc.Fe.WcfService.EfactService;
using System.Text;

namespace Mc.Fe.WcfService
{
    public class EnvioService : IEnvioService
    {

        public string EnviarPing()
        {
            string retorno = string.Empty;
            bool enviado = EmailService.EnviarCorreo("Test FElectronica", "Enviado por el servicio FElectronica.");

            if (enviado)
            {
                retorno = "Correo enviado";
            }
            else
            {

                retorno = "No se pudo enviar el correo";
            }
            return retorno;
        }

        public int EnviarDocumento()
        {
            int retorno = -1;
            try
            {
                string estado = System.Configuration.ConfigurationManager.AppSettings["EstadoEmitido"];
                string fechaDesde = System.Configuration.ConfigurationManager.AppSettings["FechaDesde"];

                var documentos = DataManager.Instance.BuscarFacturasPendientes(estado, fechaDesde);
                if (documentos.Count == 0) return -1;

                foreach (var documento in documentos)
                {
                    var documentoTipo = DataManager.Instance.BuscarFactura(documento.CodigoEmpresa, documento.CodigoTipoDocumento, documento.NumDocumento);
                    byte[] fileBytesXML;

                    if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.FACTURA) == 0 ||
                        documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.BOLETA) == 0)
                    {
                        fileBytesXML = XmlGenerator.CreateFacturaXML(documentoTipo);
                    }
                    else if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.NOTACREDITO) == 0)
                    {
                        fileBytesXML = XmlGenerator.CreateNotaCreditoXML(documentoTipo);
                    }
                    else if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.NOTADEBITO) == 0)
                    {
                        fileBytesXML = XmlGenerator.CreateNotaDebitoXML(documentoTipo);
                    }
                    else
                    {
                        return -1;
                    }

                    string url = System.Configuration.ConfigurationManager.AppSettings["WSDLEfact"];
                    string user = System.Configuration.ConfigurationManager.AppSettings["UsuarioEfact"];
                    string password = System.Configuration.ConfigurationManager.AppSettings["PasswordEfact"];

                    if (System.Configuration.ConfigurationManager.AppSettings["EnviarEfact"].CompareTo("S") == 0)
                    {
                        //Envia los documentos XML a Efact

                        /*
                        Uri ur = new Uri(url);
                        WebClient webclient = new WebClient();
                        webclient.Headers.Add("Username", user);
                        webclient.Headers.Add("Password", password);

                        //AddressingHeaders

                        //HttpWebRequest ttp = HttpWebRequest.Create(url);                        
                        
                        TransactionServiceImplService eservice = new TransactionServiceImplService();                                                                                                                        
                        NetworkCredential credential = new NetworkCredential();
                        credential.GetCredential(ur, "Basic");                       
                                                
                        //credential.Domain = null;
                        credential.UserName = user;
                        credential.Password = password;

                        WebProxy proxy = new WebProxy(url);                        
                        proxy.Credentials = credential;                                    
                        eservice.UseDefaultCredentials = true;
                        eservice.Url = url;                        
                        
                        //eservice.PreAuthenticate = true;
                        eservice.Credentials = credential;                        
                        eservice.Proxy = proxy;
                        eservice.sendPing(fileBytesXML);
                         */

                        //--------------------------------------------------
                        CqsTransactionServiceClient service = new CqsTransactionServiceClient("TransactionServiceImplPort", url);                        
                        //service.ClientCredentials.UserName.UserName = "UserName=" + "[" + user + "]";
                        //service.ClientCredentials.UserName.Password = "Password=" + "[" + password + "]";

                        Mc.Fe.WcfService.EfactService.transactionResponse response = null;
                        response = service.sendPing(fileBytesXML);
                        //response = service.sendInvoice(fileBytesXML);

                        if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.FACTURA) == 0) response = service.sendInvoice(fileBytesXML);
                        if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.BOLETA) == 0) response = service.sendBoleta(fileBytesXML);
                        if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.NOTACREDITO) == 0) response = service.sendCreditNote(fileBytesXML);
                        if (documento.CodigoTipoDocumento.CompareTo(Constantes.Catalogo01.NOTADEBITO) == 0) response = service.sendDebitNote(fileBytesXML);

                        EmailService.EnviarCorreo("FEletronica a Fecha " + DateTime.Now.ToLongDateString(), "Se ha enviado los documentos a Efact Atte: Servicio FEletronica");
                    }

                    //Guarda la tabla de control
                    DataManager.Instance.GuardarControl(documento);
                }
                retorno = 0;
            }
            catch (Exception ex)
            {
                retorno = -1;
                System.Console.Write(ex.Message);
            }

            return retorno;
        }
    }
}